<?php

/**
 * Created by PhpStorm.
 * User: jimmy
 * Date: 2017/11/3
 * Time: 下午4:04
 */
class StatController extends CloudControllerBase
{


    /******************************   本月统计   ***********************************************************/

    public function doNear6MonthPlaneStatAction()
    {

        if ($this->isMonitorAdminUser()
            || $this->isMonitorSubsystemAdminUser()
        ) {
            $sql = "select created_at,count(id) total from(
select id,DATE_FORMAT(record_at,'%Y-%m') as created_at  from plane
where
DATE_FORMAT(record_at,'%Y-%m')>
DATE_FORMAT(date_sub(curdate(), interval 6 month),'%Y-%m') and (uas_serial_id like '%FF%' or uas_serial_id like '07JD%' or uas_serial_id like '11VK%') and user_id<>7
 ) as temp
group by created_at";
            $data = $this->fetchAll($sql);
            $this->returnJson($data);
        }
    }
    
    public function doNear6MonthFlightCountAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $sql = "SELECT count(fmid) as total,created_at from 
(select f.id as fmid,
CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
			ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
			ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
(max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
max(u.stat_log_time) as time,date_format(min(u.created_at),'%Y-%m') as created_at
from flight_mission f,uas_status u,plane p 
where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%') 
and u.created_at>date_sub(curdate(), interval 6 month) $user_type_where $user_where 
group by fmid HAVING (mil>0.5 or time>300) order by fmid) as temp GROUP BY created_at";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$sql\r\n", FILE_APPEND);
        $months = $this->fetchAll($sql);
        
        $this->returnJson($months);
    }
      
    /**
     * 处理架次信息
     */
    private function _getStatLine($uasList, $filterTime = 5, $filterDistance = 0.5, $getMax = true)
    {
        $tmpUasList = array();
        
        $totalAry = array();
        
        foreach ($uasList as $uas) {            
            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);
        
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);
        
        
        $monthCount = array();
        
        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            
            if (count($_uaslist) == 1) {
                if($_uaslist [0] ['is_takeoff'] == 1){
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    if (!isset ($monthCount[$_uaslist [0]['created_at']])) {
                        $monthCount[$_uaslist [0]['created_at']] = 1;
                    }else{
                        $monthCount[$_uaslist [0]['created_at']] += 1;
                    }
                }else{
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    if (!isset ($monthCount[$_uaslist [0]['created_at']])) {
                        $monthCount[$_uaslist [0]['created_at']] = 1;
                    }else{
                        $monthCount[$_uaslist [0]['created_at']] += 1;
                    }
                }
            }
            
            foreach ($_uaslist as $_uas) {
                
                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }
                
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && $_uas ['planeModel_id'] != 3 && $_uas ['planeModel_id'] != 8) {
                    if (((intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < $filterDistance) && ($prev ['stat_log_meter'] < $filterDistance) && ($prev ['stat_log_time'] < ($filterTime * 60))) {
                        continue;
                    }
                    
                    if (!isset ($monthCount[$prev['created_at']])) {
                        $monthCount[$prev['created_at']] = 1;
                    }else{
                        $monthCount[$prev['created_at']] += 1;
                    }
                }
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && ($_uas ['planeModel_id'] == 3 || $_uas ['planeModel_id'] == 8)) {
                    if ($prev ['stat_log_meter'] < $filterDistance && $prev ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    if (!isset ($monthCount[$prev['created_at']])) {
                        $monthCount[$prev['created_at']] = 1;
                    }else{
                        $monthCount[$prev['created_at']] += 1;
                    }
                }
            }
        }
        
        return $monthCount;
    }


    public function doMonthAddUserAction()
    {
        if ($this->isMonitorAdminUser()
            || $this->isMonitorSubsystemAdminUser()
        ) {
            $sql = "select count(id) as total from(
            select id,DATE_FORMAT(created_at,'%Y-%m') as created_at  from user
where 
DATE_FORMAT(created_at,'%Y-%m')>
DATE_FORMAT(date_sub(curdate(), interval 1 month),'%Y-%m')
 ) as temp
group by created_at";
            $data = $this->fetchColumn($sql);
            $this->returnJson($data);
        }

    }

    public function doUserLoginStatAction()
    {
        $user = $this->getMonitorLoginUser(true);
        $userId = $user->userId;
        //获取登录次数
        $userCount = $this->fetchColumn("select count(id) as total from(
select id,DATE_FORMAT(created_at,'%Y-%m') as created_at  from login_record
where login_type=1 and user_id=$userId and 
DATE_FORMAT(created_at,'%Y-%m')>
DATE_FORMAT(date_sub(curdate(), interval 1 month),'%Y-%m')
 ) as temp
group by created_at");
        $userTime = $this->fetchColumn("select max(created_at) as created_at from login_record where login_type=1 and user_id=$userId");
        $this->returnJson(array(
            "login_count" => $userCount,
            "last_login" => $userTime
        ));
        //获取最后一次登录时间
    }

    private $_db = null;
    private $_whereField = array(
        'user' => '',
        'planeid' => '',
        'missionid' => '',
        'projectid' => '',
        'time' => '',
        'cellid' => '',
    );


    public function indexAction()
    {
        $token = $this->getQuery("token");
        if (!empty($token)) {
            $_SERVER["HTTP_TOKEN"] = $token;
        }
        $admin = $this->getLoginAdminUser();
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');

        $showSpace = empty($showSpace) ? 'week' : $showSpace;


        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty($startDate) ? '' : $startDate;

        $detail = array('totalMission' => '', 'totalMil' => '', 'totalPlane' => '');
        $ret = array('chartDate' => '', 'detail' => array('useTime' => '', 'milTimes' => ''));

        $fmWhere = '';

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = {$admin["id"]})";
            } else {
                $is_admin = true;
            }
        }


//        if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id';
        if (!empty($where))
            //过滤测试数据
            $sql .= ' where ' . $where . ' and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ' . $user_type_where;
        else
            $sql .= ' where  (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ' . $user_type_where;

//        $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= ' group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';
        //echo $sql;exit();
        $uasList = $this->fetchAll($sql);

        $ret = $this->_getStatDetail($uasList, $startDate, $endDate, $showSpace, $active_plane);


        $detail = array(
            'totalMission' => $ret['totalMission'],
            'totalMil' => $ret['totalMil'],
            'totalPlane' => $ret['totalPlane'],
        );

        if (!empty($ret['missionList'])) {
            $fmWhere = implode(',', $ret['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if (!empty($isGeted) && empty($fmWhere)) {
            $missionList = array();
        } else {
            $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name from flight_mission $fmWhere";
            $missionList = $this->fetchAll($missionSql);
        }


        $this->view->setVars(array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret['missionList'],
            'fsTotal' => $ret['detail']['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'chartDate' => json_encode($ret['chartDate']),
            'useTime' => json_encode($ret['detail']['useTime']),
            'milTimes' => json_encode($ret['detail']['milTimes']),
            'milTotal' => $ret['detail']['milTotal'],
            'work_areas' => $ret['detail']['workArea'],
            'work_times' => $ret['detail']['workTime'],
            "is_admin" => $is_admin,
        ));
    }

    public function selectAction()
    {
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');

        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $uasSQL = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id';
        if (!empty($where))
            $uasSQL .= ' where ' . $where . ' and uas.uas_serial_id like \'%FF%\'';
        else
            $uasSQL .= ' where  uas.uas_serial_id like \'%FF%\'';

        $uasSQL .= ' group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        $uasList = $this->fetchAll($uasSQL);

        $ret = $this->_getStatDetail($uasList, $startDate, $endDate, $showSpace, $active_plane);

        if (empty($ret))
            $this->returnError('暂无数据');
        $this->returnSuccess($ret);
    }

    public function postselectAction()
    {
        $user = $this->getPost('user');
        $uas_serial_id = $this->getPost('uas_serial_id');
        $active_user = $this->getPost('active_user');
        $active_plane = $this->getPost('active_plane');
        $mil = $this->getPost('mil');
        $startDate = $this->getPost('startDate');
        $endDate = $this->getPost('endDate');
        $showSpace = $this->getPost('showSpace');
        $planeModel = $this->getPost('planeModel');
        $admin_id = $this->getPost('is_admin');

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty ($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = $admin_id)";
            } else {
                $is_admin = true;
            }
        }

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr[] = $uasSerial['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr[] = $uasFmid['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr[] = $planeModelId['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'and uas.uas_serial_id not in (\'07JDE1700100GG\',\'07JDE2M00201UF\') group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        $uasList = $this->fetchAll($sql);

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "post admin:$admin_id, sql:$sql, uasList:" . count($uasList) . ", planeModel:$planeModel \r\n", FILE_APPEND);
        $ret = $this->_getDJStatDetail($uasList, $startDate, $endDate, $showSpace, $active_plane, $planeModel);

        if (empty ($ret))
            $this->returnError('暂无数据');
        $this->returnSuccess($ret);
    }

    public function missionInfoAction()
    {
        $id = $this->getPost('id');
        $id = intval($id);

        if (empty($id))
            $this->returnError('id不能为空');

        $sql = "select fm.id,fm.camera_type,us.uas_odometer_value,fm.average_ground_resolution,fm.high_longitudinal_overlap,fm.high_lateral_overlap,
                      fm.flight_interval,fm.take_pic_interval,fm.work_area,fm.work_time,fm.flight_relative_altitude,fm.flight_altitude,fm.default_air_speed,
                      fm.landing_method,us.is_takeoff,fm.task_coordinate_waypoints ,fm.home_lng,fm.home_lat,fm.flight_task_name,us.uas_serial_id,us.created_at,fm.user_id, plane_model.name as model
               from flight_mission as fm 
               left join uas_status as us 
               on fm.id = us.flight_mission_id
               left join plane on us.uas_serial_id = plane.uas_serial_id
               left join plane_model on plane.planeModel_id = plane_model.id
               where fm.id = $id group by us.is_takeoff";

        $info = $this->fetchAll($sql);
        if (empty($info))
            $this->returnError("mission信息为空");

        $sOdometer = 0;
        $eOdometer = 0;
        $mission = [];
        $uas_serial_id = 0;
        $stime = '';
        $etime = '';
        foreach ($info as $key => $val) {
            if ($val['is_takeoff'] == '1') {
                $stime = date('H:i', strtotime($val['created_at']));
                $sOdometer = $val['uas_odometer_value'];
            } else {
                $eOdometer = $val['uas_odometer_value'];
                $etime = date('H:i', strtotime($val['created_at']));
                $mission = $val;
            }
        }

        $sql = "select company from user where id={$mission['user_id']}";
        $company = $this->fetchOne($sql)['company'];

        $mission['work_mil'] = $eOdometer - $sOdometer;
        $mission['company'] = $company;
        $mission['flightTime'] = "$stime-$etime";
        $mission['created_at'] = date('Y-m-d', strtotime($mission['created_at']));

        $this->returnSuccess($mission);
    }


    private function _createWhere($user, $uas_serial_id, $startDate, $endDate, $joinname = '', $planeModel)
    {
        $where = '';
        $phoneIn = '';

        if (!empty($joinname))
            $joinname = $joinname . '.';

        //通过user获取
        if (!empty($user)) {
            $userSQL = "select phone from user where nickname like '%$user%'";
            $userList = $this->fetchAll($userSQL);
            if (!empty($userList)) {
                foreach ($userList as $_user) {
                    $phoneIn .= $_user['phone'] . '\',\'';
                }
            }

            if (!empty($phoneIn))
                $phoneIn = rtrim($phoneIn, '\',\'');

            $userWhere = '';
            if (!empty($phoneIn))
                $userWhere = " phone in ('$phoneIn') ";

            $userWhere .= " or phone like '%$user%'";

            $userWhere = trim($userWhere);
            $userWhere = ltrim($userWhere, 'or');
            $userWhere = "where $userWhere";

            $uasPhoneSQL = "select id from flight_mission $userWhere";

            $flightMissions = $this->fetchAll($uasPhoneSQL);
            $flightMissionIN = "";
            if (!empty($flightMissions)) {
                foreach ($flightMissions as $ms) {
                    $flightMissionIN .= $ms['id'] . '\',\'';
                }
            }

            if (!empty($flightMissionIN))
                $flightMissionIN = rtrim($flightMissionIN, '\',\'');

            $where .= "  {$joinname}flight_mission_id in('$flightMissionIN') ";


        }


        if (!empty($uas_serial_id)) {
            $uas_serial_id = trim($uas_serial_id);
            if (preg_match('/([^\da-z])/i', $uas_serial_id, $find)) {
                $uasIdList = explode($find[0], $uas_serial_id);
                foreach ($uasIdList as $key => $uasId) {
                    if (empty(trim($uasId)))
                        unset($uasIdList[$key]);
                }
                $uas_serial_id = implode("','", $uasIdList);
                $where .= " and {$joinname}uas_serial_id in ('$uas_serial_id') ";
            } else {
                $where .= " and {$joinname}uas_serial_id like '%$uas_serial_id%' ";
            }
        }

        if (!empty($planeModel)) {
            $where .= " and planeModel_id = $planeModel ";
        }

        //通过飞机编号查询
//        $where .= !empty($uas_serial_id) ? " and {$joinname}uas_serial_id like '%$uas_serial_id%'" : '';
//        $where .= !empty($startDate) ? " and {$joinname}created_at >= '$startDate 00:00:00' " : " and {$joinname}created_at >= '1970-01-01 08:00:00' ";
        $where .= !empty($startDate) ? " and {$joinname}created_at >= '$startDate 00:00:00' " : '';
        $where .= !empty($endDate) ? " and {$joinname}created_at <= '$endDate 23:59:59' " : '';

        $where = trim($where);
        $where = ltrim($where, 'and');
        return $where;
    }


    private function _getStatDetail($uasList, $startTime, $endTime, $showSpace, $active_plane = false, $getMax = true)
    {

        $startTime = !empty($startTime) ? strtotime($startTime) : '';
        $endTime = !empty($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();
        if (!empty($active_plane)) {
            $activePlaneAry = array();
            $activeMissions = array();
            foreach ($uasList as $u) {
                $activePlaneAry[$u['uas_serial_id']][] = $u['flight_sorties'];
                $activeMissions[$u['uas_serial_id']][] = $u['flight_mission_id'];

            }
            $tmpActive = array();
            $tmpSort = array();
            foreach ($activePlaneAry as $key => $active) {
                if (count($active) < 2) {
                    unset($activePlaneAry[$key]);
                    continue;
                }

                $tmpActive[$key] = max($active);
            }
            arsort($tmpActive);

            $activeLength = count($tmpActive);

            if ($active_plane > $activeLength)
                $active_plane = $activeLength;

            $tmpActive = array_slice($tmpActive, 0, $active_plane, true);

            $tmpActiveKeys = array_keys($tmpActive);
            $tmpMiss = array();
            foreach ($tmpActiveKeys as $ak => $uas_serial_id) {
                if (!isset($activeMissions[$uas_serial_id]))
                    continue;
                $tmpMiss = array_merge($tmpMiss, $activeMissions[$uas_serial_id]);
            }

            foreach ($uasList as $k => $v) {
                if (!in_array($v['flight_mission_id'], $tmpMiss)) {
                    unset($uasList[$k]);
                }
            }
        }


        foreach ($uasList as $uas) {
            $tmpUasList[$uas['flight_mission_id']][] = $uas;
            $totalAry[$uas['uas_serial_id']][] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry[] = $val['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems[] = $total[0];
        }
        unset($dateAry);

        $totalMil = 0;
        $totalMission = 0;
        $totalPlane = count($totalItems);
        foreach ($totalItems as $item) {
            $totalMil += $item['uas_odometer_value'];
            $totalMission += $item['flight_sorties'];
        }


        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();


        $totalMissionAry = array();
        $fsTotal = 0;
        $c = 0;
        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;
            $itemMission = 0;
            foreach ($_uaslist as $_uas) {

                if (empty($prev)) {
                    $prev = $_uas;
                    continue;
                }

                $itemMissionAry[$_uas['uas_serial_id']]['flight_sorties'][] = $_uas['flight_sorties'];
                $milAry[$_uas['uas_serial_id']]['mil'][] = $_uas['uas_odometer_value'];
                $totalPlaneAry[$_uas['uas_serial_id']] = 1;
                //&& $_uas['uas_serial_id'] == 'ZFFFCGLS16100011'
                if ($prev['is_takeoff'] == 1 && empty($_uas['is_takeoff'])) {

                    $missions[] = $_uas['flight_mission_id'];

                    $sumMil = intval($_uas['uas_odometer_value']) - intval($prev['uas_odometer_value']);

                    $fsTotal += intval($_uas['flight_sorties']) - intval($prev['flight_sorties']);
                    list($dkey) = explode(' ', $_uas['created_at']);
                    if (!isset($chartData[$dkey])) {
                        continue;
                    }

                    if (!isset($useTime[$chartData[$dkey]]))
                        $useTime[$chartData[$dkey]] = 0;
                    $useTime[$chartData[$dkey]] += 1;

                    if (!isset($itemMilAry[$chartData[$dkey]]))
                        $itemMilAry[$chartData[$dkey]] = 0;
                    $itemMilAry[$chartData[$dkey]] += $sumMil;
                }
            }
            $totalMission += $itemMission;
        }


        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset($useTime[$date]))
                $useTime[$date] = 0;

            if (!isset($itemMilAry[$date]))
                $itemMilAry[$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);

        $fsTotal = array_sum($useTime);

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0,
        ];

        if (!empty($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            $missionRet = $this->fetchOne($missionsSql);
        }

//        $chartDataTmp = array_reverse($chartDataTmp);
//        $useTime = array_reverse($useTime);
//        $itemMilAry = array_reverse($itemMilAry);

        return array(
            'missionList' => $missions,
            'totalPlane' => $totalPlane,
            'totalMil' => $totalMil,
            'totalMission' => $totalMission,
            'chartDate' => $chartDataTmp,
            'detail' => array(
                'useTime' => array_values($useTime),
                'milTimes' => array_values($itemMilAry),
                'milTotal' => array_sum($itemMilAry),
                'fsTotal' => $fsTotal,
                'workArea' => $missionRet['work_areas'],
                'workTime' => $missionRet['work_times']
            )
        );


    }

    private function _getDJStatDetail($uasList, $startTime, $endTime, $showSpace, $active_plane = false, $planeModel = null, $getMax = true)
    {
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();
        if (!empty ($active_plane)) {
            $activePlaneAry = array();
            $activeMissions = array();
            foreach ($uasList as $u) {
                $activePlaneAry [$u ['uas_serial_id']] [] = $u ['flight_sorties'];
                $activeMissions [$u ['uas_serial_id']] [] = $u ['flight_mission_id'];
            }
            $tmpActive = array();
            $tmpSort = array();
            foreach ($activePlaneAry as $key => $active) {
                if (count($active) < 2) {
                    unset ($activePlaneAry [$key]);
                    continue;
                }

                $tmpActive [$key] = max($active);
            }
            arsort($tmpActive);

            $activeLength = count($tmpActive);

            if ($active_plane > $activeLength)
                $active_plane = $activeLength;

            $tmpActive = array_slice($tmpActive, 0, $active_plane, true);

            $tmpActiveKeys = array_keys($tmpActive);
            $tmpMiss = array();
            foreach ($tmpActiveKeys as $ak => $uas_serial_id) {
                if (!isset ($activeMissions [$uas_serial_id]))
                    continue;
                $tmpMiss = array_merge($tmpMiss, $activeMissions [$uas_serial_id]);
            }

            foreach ($uasList as $k => $v) {
                if (!in_array($v ['flight_mission_id'], $tmpMiss)) {
                    unset ($uasList [$k]);
                }
            }
        }

        foreach ($uasList as $uas) {
            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);

        $totalMil = 0;
        $totalMission = 0;
        $totalPlane = count($totalItems);
        foreach ($totalItems as $item) {
            $totalMil += $item ['uas_odometer_value'];
            $totalMission += $item ['flight_sorties'];
        }

        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();

        $totalMissionAry = array();
        $fsTotal = 0;
        $c = 0;
        $endcount = 0;
        $endmil = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);
        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;
            $itemMission = 0;
            foreach ($_uaslist as $_uas) {

                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }

                $itemMissionAry [$_uas ['uas_serial_id']] ['flight_sorties'] [] = $_uas ['flight_sorties'];
                $milAry [$_uas ['uas_serial_id']] ['mil'] [] = $_uas ['uas_odometer_value'];
                $totalPlaneAry [$_uas ['uas_serial_id']] = 1;
                // && $_uas['uas_serial_id'] == 'ZFFFCGLS16100011'
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff'])) {

                    $missions [] = $_uas ['flight_mission_id'];

                    $sumMil = intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value']);

                    $fsTotal += intval($_uas ['flight_sorties']) - intval($prev ['flight_sorties']);


                    $endmil += intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value']);
//                     $totalMil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );

                    $endcount = $endcount + 1;
//                     $sumMil = intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );

//                     $fsTotal += intval ( $_uas ['flight_sorties'] ) - intval ( $prev ['flight_sorties'] );

//                     $time =  strtotime($_uas ['created_at']) - strtotime($prev['created_at']);

//                     file_put_contents("./log_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."model planeModel:$planeModel,end:{$_uas ['created_at']},start:{$prev['created_at']}\r\n", FILE_APPEND);
//                     if($planeModel == '3'){

//                         $missions [] = $_uas ['flight_mission_id'];
//                         $taskIdSql = "select flight_task_id from flight_mission where id=".$_uas ['flight_mission_id'];
//                         $taskids = $this->fetchOne( $taskIdSql );
//                         file_put_contents("./log_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."sql taskIdqdl:$taskIdSql\r\n", FILE_APPEND);

//                         $taskWhere= " where local_id = '".$taskids['flight_task_id']."'";

//                         $taskSql = "select total_mileage from flight_task $taskWhere";
//                         $taskList = $this->fetchOne( $taskSql );

//                         $sumMil = $taskList['total_mileage'];
//                         $fsTotal +=1;
//                     }else if($planeModel != '3'){
//                         $missions [] = $_uas ['flight_mission_id'];
//                     }

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
                if ($planeModel == 3)
                    $itemMission = 1;
            }
            $totalMission += $itemMission;
        }

        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset ($useTime [$date]))
                $useTime [$date] = 0;

            if (!isset ($itemMilAry [$date]))
                $itemMilAry [$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);

        $fsTotal = array_sum($useTime);

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0
        ];

        if (!empty ($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$missionsSql\r\n", FILE_APPEND);
            $missionRet = $this->fetchOne($missionsSql);
        }

        // $chartDataTmp = array_reverse($chartDataTmp);
        // $useTime = array_reverse($useTime);
        // $itemMilAry = array_reverse($itemMilAry);

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count endmil:$endmil, endcount:$endcount \r\n", FILE_APPEND);

        return array(
            'missionList' => $missions,
            'totalPlane' => $totalPlane,
            'totalMil' => $totalMil,
            'totalMission' => $totalMission,
            'chartDate' => $chartDataTmp,
            'detail' => array(
                'useTime' => array_values($useTime),
                'milTimes' => array_values($itemMilAry),
                'milTotal' => array_sum($itemMilAry),
                'fsTotal' => $fsTotal,
                'workArea' => $missionRet ['work_areas'],
                'workTime' => $missionRet ['work_times']
            )
        );
    }

    private function _createChartData($stime = false, $etime = false, $showSpace = 'week')
    {
        $etime = empty($etime) ? time() : $etime;

        $isuse1970 = !empty($stime) ? false : true;

        $stime = empty($stime) ? strtotime('2016-01-03') : $stime;

        $wtime = $stime;
        $dateRet = array();
        $day = 0;
        $ctime = time();

        $_showSpace = $showSpace == 'week' ? 7 : 1;
        while (1) {
            if ($day % $_showSpace == 0)
                if ($showSpace == 'week') {
                    $wtime = $stime + ($day + 7) * 86400;
                    $wtime = $wtime > $ctime ? $ctime : $wtime;
                } else
                    $wtime = $stime + $day * 86400;

            $wkey = date('Y-m-d', $wtime);
            $dtime = $stime + $day * 86400;
            $dkey = date('Y-m-d', $dtime);

            if ($dtime >= $etime)
                break;

            $dateRet[$dkey] = $wkey;
            $day++;
        }

        if ($isuse1970)
            $dateRet = array_merge(array('1970-01-01' => '1970-01-07'), $dateRet);

        return $dateRet;
    }

    /**
     * 请求实时架次信息
     */
    public function requestFlightingCountAction()
    {
        //时间间隔
        $timeInterval = -2;

        $sql = "SELECT m.*
FROM (SELECT *
      FROM (SELECT
              m.id,
              m.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name,
                           count(*) AS flight_count
            FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id
            WHERE NOT u.id IS NULL 
            GROUP BY m.id) AS temp
      WHERE created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND flight_count = 1

)as m
  INNER JOIN (
   SELECT * from (
        
    SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -2 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp 
    
    GROUP by uas_serial_id  
  
  
  ) as u on  m.id = u.flight_mission_id";
        header('Content-type: application/json');
        header('Access-Control-Allow-Origin:*');
        $data = $this->fetchAll($sql);
        
        $records =  array();
        
        foreach($data as $onAir){
            $sql = "SELECT local_id FROM flight_mission where id = " . $onAir['id'];
            $fmid = $this->fetchColumn( $sql );
            
            if(!empty($fmid)&&$this->redis->exists('detail-upload-fmid-'.$fmid)){
                $records[]= $onAir;
            }
        }
        
        file_put_contents("./onAir_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "records:".count($records)."\r\n", FILE_APPEND);
        
        $this->returnJson($records);
    }

    public function statNewAction()
    {

        $this->indexAction();
    }


    public function statCloudAction()
    {
        $this->indexAction();
    }

    /**
     * 飞机统计数量
     */
    public function monthAddAction()
    {
        $monthAddSql = "SELECT count(*) as total from plane WHERE  created_at>=DATE_ADD(curdate(),interval -day(curdate())+1 day)";
        header('Content-type: application/json');
        header('Access-Control-Allow-Origin:*');
        $data = $this->fetchOne($monthAddSql);
        $this->returnJson($data);
    }

    /**
     * 飞机统计数量
     */
    public function flightMonthAddAction()
    {
        $planeModel = $this->request->get('planeModel');
        $where = '';
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "planeModel:$planeModel\r\n", FILE_APPEND);
        if (!empty($planeModel)) {
            $where = "planeModel_id=$planeModel and";
        }
        $monthAddSql = "SELECT count(*) as total from plane WHERE $where created_at>=DATE_ADD(curdate(),interval -day(curdate())+1 day)";
        header('Content-type: application/json');
        header('Access-Control-Allow-Origin:*');
        $data = $this->fetchOne($monthAddSql);
        $this->returnJson($data);
    }

    /**
     * 获取block详细信息
     */
    public function requestBlockDetailAction()
    {
        $missionId = $this->request->get('id');
        $sql = "select * from flight_mission WHERE id=$missionId";

        $data = $this->fetchOne($sql);
        $PlaneSql = "SELECT temp.uas_serial_id,plane.phone from (
SELECT uas_serial_id from uas_status WHERE flight_mission_id=$missionId
  and uas_serial_id is NOT null
GROUP by uas_serial_id
    ) as temp  left JOIN plane on plane.uas_serial_id=temp.uas_serial_id
    ";
        $planeInfoData = $this->fetchOne($PlaneSql);
        $this->returnJson(array(
            'block_info' => $data,
            'plane_info' => $planeInfoData
        ));
    }

    public function multiScreenAction()
    {


    }

    public function subScreenAction()
    {
        $missionId = $this->request->get('mission');
        if (!empty($missionId)) {
            $sql = "select * from flight_mission WHERE id=$missionId";
            $data = $this->fetchOne($sql);

            $userSql = "SELECT nickname,phone,icon_url FROM user WHERE id={$data['user_id']}";
            $userData = $this->fetchOne($userSql);

            $statusData = $this->fetchAll("SELECT uas_serial_id FROM uas_status WHERE flight_mission_id='{$data['id']}'");
            if ($userData["icon_url"]){
                $iconUrl = $userData["icon_url"];
            }else {
                $iconUrl = "/images/main/main_user_icon.png";
            }

            $this->view->setVars(array(
                'missionDetail' => json_encode($data),
                'location' => $data["country"] . "-" . $data["city"] . "-" . $data["district"],
                "planeType" => $data["plane_type"],
                "uasSerialId" => $statusData[0]["uas_serial_id"],
                "userInfo" => $userData,
                "userIcon" => $iconUrl,
                'socket' => $this->host['missionSocket'],
            ));



        }




    }

    public function f200Action()
    {
        $admin = $this->getLoginAdminUser();
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $detail = array(
            'totalMission' => '',
            'totalMil' => '',
            'totalPlane' => ''
        );
        $ret = array(
            'chartDate' => '',
            'detail' => array(
                'useTime' => '',
                'milTimes' => ''
            )
        );

        $fmWhere = '';

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty ($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = {$admin["id"]})";
            } else {
                $is_admin = true;
            }
        }

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr[] = $uasSerial['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr[] = $uasFmid['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr[] = $planeModelId['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        // echo $sql;exit();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count sql:$sql \r\n", FILE_APPEND);
        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count uasList:" . count($uasList) . ", planeModel:$planeModel \r\n", FILE_APPEND);
        $ret = $this->_getDJStatDetail($uasList, $startDate, $endDate, $showSpace, $active_plane, $planeModel);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "ret ret_json:" . json_encode($ret) . "\r\n", FILE_APPEND);
        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        if (!empty ($ret ['missionList'])) {
            $fmWhere = implode(',', $ret ['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if ($planeModel == '3' && !empty ($ret ['missionList'])) {
            $taskIdSql = "select flight_task_id from flight_mission $fmWhere";
            $taskids = $this->fetchAll($taskIdSql);

            foreach ($taskids as $taskid) {
                $taskidWhere[] = $taskid['flight_task_id'];
            }

            $taskWhere = implode("','", $taskidWhere);
            $taskWhere = " where local_id in ('$taskWhere')";

            $taskSql = "select total_mileage from flight_task $taskWhere";
            $taskLists = $this->fetchAll($taskSql);
            foreach ($taskLists as $taskList) {
                if ($taskList['total_mileage'] < 30)
                    $taskListmil += $taskList['total_mileage'];
            }
            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "model3 sql:$taskSql \r\n", FILE_APPEND);

            $detail['totalMil'] = $taskListmil;
        }

        if (!empty ($isGeted) && empty ($fmWhere)) {
            $missionList = array();
        } else {
            $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name from flight_mission $fmWhere";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "home sql:$missionSql\r\n", FILE_APPEND);
            $missionList = $this->fetchAll($missionSql);
        }

        $arr = array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret ['missionList'],
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_user' => $active_user,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime'],
            "is_admin" => $admin["id"]
        );

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "return json:" . json_encode($arr) . "\r\n", FILE_APPEND);

        $this->view->setVars(array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret ['missionList'],
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_user' => $active_user,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime'],
            "is_admin" => $admin["id"]
        ));
    }

    public function statFlightAction()
    {
        $admin = $this->getLoginAdminUser();
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $warrantyAt = $this->request->get('warrantyAt');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        if ($filterTime !== '0') {
            $filterTime = empty($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $detail = array(
            'totalMission' => '',
            'totalMil' => '',
            'totalPlane' => ''
        );
        $ret = array(
            'chartDate' => '',
            'detail' => array(
                'useTime' => '',
                'milTimes' => ''
            )
        );

        $fmWhere = '';

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = {$admin["id"]}) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty ($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = {$admin["id"]})";
            } else {
                $is_admin = true;
            }
        }

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr [] = $uasSerial ['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty ($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        if ($landingMethod === '0') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method = 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }
        if ($landingMethod == '1') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method <> 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }

        if ($warrantyAt === '0') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at<='" . date('Y-m-d') . "' and type<>0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }
        if ($warrantyAt == '1') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at>'" . date('Y-m-d') . "' or type=0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr [] = $uasFmid ['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty ($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $timeInterval = -1;
        $sql_onAir_fmid = 'SELECT m.id FROM (SELECT * FROM (SELECT m.id, u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name, count(*) AS flight_count FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id WHERE NOT u.id IS NULL GROUP BY m.id) AS temp WHERE created_at >= date_add(now(), INTERVAL - 1 HOUR) AND flight_count = 1)as m INNER JOIN (SELECT * from (SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -1 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp GROUP by uas_serial_id) as u on  m.id = u.flight_mission_id';
        $uasOnAirFmidList = $this->fetchAll($sql_onAir_fmid);
        foreach ($uasOnAirFmidList as $uasOnAirFmid) {
            if (in_array($uasOnAirFmid ['id'], $uas_fmid_arr)) {
                $flag = $uasOnAirFmid ['id'];
            }
            $uas_OnAirfmid_arr [] = $uasOnAirFmid ['id'];
        }
        $uas_OnAirfmid_ids = implode(',', $uas_OnAirfmid_arr);
        if (!empty ($uas_OnAirfmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_OnAirfmid_ids) ";
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr [] = $planeModelId ['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        // echo $sql;exit();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count sql:$sql \r\n", FILE_APPEND);
        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count uasList:" . count($uasList) . ", planeModel:$planeModel \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, landingMethod:$landingMethod, warrantyAt:$warrantyAt, filterTime:$filterTime, filterDistance:$filterDistance, active_plane:$active_plane\r\n", FILE_APPEND);
        $ret = $this->_getF200StatDetail($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance, $active_plane);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "ret ret_json:" . json_encode($ret) . "\r\n", FILE_APPEND);
        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        if (!empty ($ret ['missionList'])) {
            $fmWhere = implode(',', $ret ['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if (!empty ($isGeted) && empty ($fmWhere)) {
            $missionList = array();
        } else {
            if (empty($fmWhere)) {
                $missionList = array();
            } else {
                $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name from flight_mission $fmWhere";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "home sql:$missionSql\r\n", FILE_APPEND);
                $missionList = $this->fetchAll($missionSql);
            }
        }

        $arr = array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret ['missionList'],
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_user' => $active_user,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'landingMethod' => $landingMethod,
            'warrantyAt' => $warrantyAt,
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime'],
            "is_admin" => $admin["id"]
        );

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "return json:" . json_encode($arr) . "\r\n", FILE_APPEND);

        $this->view->setVars(array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret ['missionList'],
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_user' => $active_user,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'landingMethod' => $landingMethod,
            'warrantyAt' => $warrantyAt,
            'filterTime' => $filterTime,
            'filterDistance' => ($filterDistance * 1000),
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime'],
            "is_admin" => $admin ["id"]
        ));
    }

    public function statselectAction()
    {
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $warrantyAt = $this->request->get('warrantyAt');
        $admin_id = $this->request->get('is_admin');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "select user:$user, uas_serial_id:$uas_serial_id, mil:$mil, planeModel:$planeModel, landingMethod:$landingMethod, warrantyAt:$warrantyAt, is_admin:$admin_id, filterTime:$filterTime, filterDistance:$filterDistance, startDate:$startDate, endDate:$endDate\r\n", FILE_APPEND);

        if ($filterTime !== '0') {
            $filterTime = empty($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }


        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty ($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = $admin_id)";
            } else {
                $is_admin = true;
            }
        }

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr[] = $uasSerial['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        if ($landingMethod === '0') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method = 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }
        if ($landingMethod == '1') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method <> 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }

        if ($warrantyAt === '0') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at<='" . date('Y-m-d') . "' and type<>0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }
        if ($warrantyAt == '1') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at>'" . date('Y-m-d') . "' or type=0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr[] = $uasFmid['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $timeInterval = -1;
        $sql_onAir_fmid = 'SELECT m.id FROM (SELECT * FROM (SELECT m.id, u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name, count(*) AS flight_count FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id WHERE NOT u.id IS NULL GROUP BY m.id) AS temp WHERE created_at >= date_add(now(), INTERVAL - 1 HOUR) AND flight_count = 1)as m INNER JOIN (SELECT * from (SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -1 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp GROUP by uas_serial_id) as u on  m.id = u.flight_mission_id';
        $uasOnAirFmidList = $this->fetchAll($sql_onAir_fmid);
        foreach ($uasOnAirFmidList as $uasOnAirFmid) {
            if (in_array($uasOnAirFmid ['id'], $uas_fmid_arr)) {
                $flag = $uasOnAirFmid ['id'];
            }
            $uas_OnAirfmid_arr [] = $uasOnAirFmid ['id'];
        }
        $uas_OnAirfmid_ids = implode(',', $uas_OnAirfmid_arr);
        if (!empty ($uas_OnAirfmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_OnAirfmid_ids) ";
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr[] = $planeModelId['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "post admin:$admin_id, sql:$sql, uasList:" . count($uasList) . ", planeModel:$planeModel \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, filterTime:$filterTime, filterDistance:$filterDistance, active_plane:$active_plane\r\n", FILE_APPEND);
        $ret = $this->_getF200StatDetail($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance, $active_plane);

        if (empty ($ret))
            $this->returnError('暂无数据');
        $this->returnSuccess($ret);
    }

    public function searchStatAction()
    {
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $active_user = $this->request->get('active_user');
        $active_plane = $this->request->get('active_plane');
        $mil = $this->request->get('mil');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $warrantyAt = $this->request->get('warrantyAt');
        $admin_id = $this->request->get('is_admin');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "select user:$user, uas_serial_id:$uas_serial_id, mil:$mil, planeModel:$planeModel, landingMethod:$landingMethod, warrantyAt:$warrantyAt, is_admin:$admin_id, filterTime:$filterTime, filterDistance:$filterDistance, startDate:$startDate, endDate:$endDate\r\n", FILE_APPEND);
        if ($filterTime !== '0') {
            $filterTime = empty($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }


        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $active_plane || $mil || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $is_admin = false;
        $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_SUPER_ADMIN%'";
        $user_type_where = "";
        if ($record = $this->fetchOne($sql)) {

            $is_admin = true;
        } else {
            $sql = "select * from (SELECT a.username, a.roles as user_roles, c.roles as group_roles FROM `fos_user_user` as a left join fos_user_user_group as b on a.id = b.user_id left join fos_user_group as c on b.group_id = c.id where a.id = $admin_id) as b where user_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%' or group_roles like '%ROLE_THEWBB_ADMIN_ADMIN_ANALYSIS_PLANE_MASTER%'";
            $record = $this->fetchOne($sql);
            if (empty ($record)) {
                $user_type_where = " and plane.id in (select plane_id from developer_project inner join developer_project_flight on developer_project.id = developer_project_flight.developer_project_id where admin_user_id = $admin_id)";
            } else {
                $is_admin = true;
            }
        }

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr[] = $uasSerial['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        if ($landingMethod === '0') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method = 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }
        if ($landingMethod == '1') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method <> 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }

        if ($warrantyAt === '0') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at<='" . date('Y-m-d') . "' and type<>0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }
        if ($warrantyAt == '1') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at>'" . date('Y-m-d') . "' or type=0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr[] = $uasFmid['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $timeInterval = -1;
        $sql_onAir_fmid = 'SELECT m.id FROM (SELECT * FROM (SELECT m.id, u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name, count(*) AS flight_count FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id WHERE NOT u.id IS NULL GROUP BY m.id) AS temp WHERE created_at >= date_add(now(), INTERVAL - 1 HOUR) AND flight_count = 1)as m INNER JOIN (SELECT * from (SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -1 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp GROUP by uas_serial_id) as u on  m.id = u.flight_mission_id';
        $uasOnAirFmidList = $this->fetchAll($sql_onAir_fmid);
        foreach ($uasOnAirFmidList as $uasOnAirFmid) {
            if (in_array($uasOnAirFmid ['id'], $uas_fmid_arr)) {
                $flag = $uasOnAirFmid ['id'];
            }
            $uas_OnAirfmid_arr [] = $uasOnAirFmid ['id'];
        }
        $uas_OnAirfmid_ids = implode(',', $uas_OnAirfmid_arr);
        if (!empty ($uas_OnAirfmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_OnAirfmid_ids) ";
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr[] = $planeModelId['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "post admin:$admin_id, sql:$sql, uasList:" . count($uasList) . ", planeModel:$planeModel \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, filterTime:$filterTime, filterDistance:$filterDistance, active_plane:$active_plane\r\n", FILE_APPEND);
        $ret = $this->_getF200StatDetail($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance, $active_plane);

        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        if (!empty ($ret ['missionList'])) {
            $fmWhere = implode(',', $ret ['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if (!empty ($isGeted) && empty ($fmWhere)) {
            $missionList = array();
        } else {
            if (empty($fmWhere)) {
                $missionList = array();
            } else {
                $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name from flight_mission $fmWhere";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "home sql:$missionSql\r\n", FILE_APPEND);
                $missionList = $this->fetchAll($missionSql);
            }
        }

        $arr = array(
            'missionList' => json_encode($missionList),
            'missionArray' => $missionList,
            'useMissionList' => $ret ['missionList'],
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'active_user' => $active_user,
            'active_plane' => $active_plane,
            'mil' => $mil,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'landingMethod' => $landingMethod,
            'warrantyAt' => $warrantyAt,
            'filterTime' => $filterTime,
            'filterDistance' => ($filterDistance * 1000),
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime'],
            "is_admin" => $admin_id
        );

        if (empty ($ret))
            $this->returnError('暂无数据');
        $this->returnJson($arr);
    }

    private function _getF200StatDetail($uasList, $startTime, $endTime, $showSpace, $filterTime = 5, $filterDistance = 0.5, $active_plane = false, $getMax = true)
    {
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();

        foreach ($uasList as $uas) {
            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);

        $totalMil = 0;
        $totalPlane = count($totalItems);
        $workTime = 0;
//         foreach ( $totalItems as $item ) {
//             // $totalMil += $item ['uas_odometer_value'];
//             if ($item ['planeModel_id'] != '3')
//                 $totalMission += $item ['flight_sorties'];
//         }

        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();

        $totalMissionAry = array();
        $fsTotal = 0;
        $c = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);

        $offcount = 0;
        $offmil = 0;
        $endcount = 0;
        $endmil = 0;

        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;

            if (count($_uaslist) == 1) {
                if ($_uaslist [0] ['is_takeoff'] == 1) {//处理只有起飞没有降落架次
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < $filterTime * 60) {
                        continue;
                    }

                    $missionsTakeOff [] = $_uaslist [0] ['id'];
                    $missions [] = $_uaslist [0] ['flight_mission_id'];

                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }

                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);

                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;

                    $fsTotal += 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                } else {//处理只有降落没有起飞架次
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < $filterTime * 60) {
                        continue;
                    }

                    $missionsTakeOff [] = $_uaslist [0] ['id'];
                    $missions [] = $_uaslist [0] ['flight_mission_id'];

                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }

                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);

                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;

                    $fsTotal += 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
            }

            foreach ($_uaslist as $_uas) {

                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }

                // $itemMissionAry [$_uas ['uas_serial_id']] ['flight_sorties'] [] = $_uas ['flight_sorties'];
                // $milAry [$_uas ['uas_serial_id']] ['mil'] [] = $_uas ['uas_odometer_value'];
                // $totalPlaneAry [$_uas ['uas_serial_id']] = 1;
                // && $_uas['uas_serial_id'] == 'ZFFFCGLS16100011'

                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && $_uas ['planeModel_id'] != 3 && $_uas ['planeModel_id'] != 8) {
                    if (((intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < $filterDistance) && ($prev ['stat_log_meter'] < $filterDistance) && ($prev ['stat_log_time'] < ($filterTime * 60))) {
                        continue;
                    }

                    $missionsTakeEnd [] = $_uas['id'];
                    $missions [] = $_uas ['flight_mission_id'];
                    if ($prev ['stat_log_time'] > 0 && (intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) > 200) {//飞控跳变,使用飞行日志
                        $workTime += ($prev ['stat_log_time'] / 3600);
                        $missionsF200s [] = $_uas ['id'];

                        $sumMil = $prev ['stat_log_meter'];
                        $endmil += $prev ['stat_log_meter'];
                        $totalMil += $prev ['stat_log_meter'];
                    } else {
//                         $flag = $prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ));
                        if ($prev ['stat_log_meter'] * 100 / (intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < 95) {
                            $missionsF200 [] = $_uas ['flight_mission_id'];
                        } else {
                            $missionsstat [] = $_uas ['flight_mission_id'];
                            $stat_time += ($prev ['stat_log_time'] / 3600);
                            $workTime += ($prev ['stat_log_time'] / 3600);
                        }

                        $missionsF200s [] = $_uas ['id'];

                        $sumMil = intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value']);
                        $endmil += intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value']);
                        $totalMil += intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value']);
                    }

//                     $fsTotal += intval ( $_uas ['flight_sorties'] ) - intval ( $prev ['flight_sorties'] );
                    $fsTotal += 1;

                    $endcount = $endcount + 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && ($_uas ['planeModel_id'] == 3 || $_uas ['planeModel_id'] == 8)) {
                    if ($prev ['stat_log_meter'] < $filterDistance && $prev ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    $missionsTakeEnd [] = $_uas['id'];

                    $missions [] = $_uas ['flight_mission_id'];
                    $missionsD1000 [] = $_uas ['id'];

                    $sumMil = intval($prev ['stat_log_meter']);

                    $fsTotal += 1;

                    $totalMil += $prev ['stat_log_meter'];
                    $workTime += ($prev ['stat_log_time'] / 3600);

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }

                // if ($planeModel == 3)
                // $itemMission = 1;
            }
        }

        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset ($useTime [$date]))
                $useTime [$date] = 0;

            if (!isset ($itemMilAry [$date]))
                $itemMilAry [$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);

//         $fsTotal = array_sum ( $useTime );

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0
        ];
        $missionF200Ret = [
            'work_areas' => 0,
            'work_times' => 0
        ];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time workTime:$workTime\r\n", FILE_APPEND);

        if (!empty ($missionsF200)) {
            $missionsF200In = implode(",", $missionsF200);
            $missionsF200Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsF200In)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time F200_mid:$missionsF200Sql\r\n", FILE_APPEND);
            $missionF200Ret = $this->fetchOne($missionsF200Sql);
        }

        if (!empty ($missionsF200s)) {
            $missionsF200Ins = implode(",", $missionsF200s);
            $missionsF200Sqls = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsF200Ins)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time F200_sid:$missionsF200Sqls\r\n", FILE_APPEND);
        }

        if (!empty ($missionsD1000)) {
            $missionsD1000In = implode(",", $missionsD1000);
            $missionsD1000Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsD1000In)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time D1000_ids:$missionsD1000Sql\r\n", FILE_APPEND);
//             $missionF200Ret = $this->fetchOne ( $missionsSql );
        }

        if (!empty ($missionsTakeOff)) {
            $missionsTakeOffIn = implode(",", $missionsTakeOff);
            $missionsTakeOffSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsTakeOffIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time takeOff_ids:$missionsTakeOffSql\r\n", FILE_APPEND);
            //             $missionF200Ret = $this->fetchOne ( $missionsSql );
        }

        if (!empty ($missionsTakeEnd)) {
            $missionsTakeEndIn = implode(",", $missionsTakeEnd);
            $missionsTakeEndSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsTakeEndIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time takeEnd_ids:$missionsTakeEndSql\r\n", FILE_APPEND);
            //             $missionF200Ret = $this->fetchOne ( $missionsSql );
        }

        if (!empty ($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$missionsSql\r\n", FILE_APPEND);
            $missionRet = $this->fetchOne($missionsSql);
        }


        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count offmil:$offmil, offcount:$offcount\r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count endmil:$endmil, endcount:$endcount \r\n", FILE_APPEND);

        // $chartDataTmp = array_reverse($chartDataTmp);
        // $useTime = array_reverse($useTime);
        // $itemMilAry = array_reverse($itemMilAry);

        $m = $workTime;
        return array(
            'missionList' => $missions,
            'totalPlane' => $totalPlane,
            'totalMil' => round($totalMil, 2),
            'totalMission' => $fsTotal,
            'chartDate' => $chartDataTmp,
            'detail' => array(
                'useTime' => array_values($useTime),
                'milTimes' => array_values($itemMilAry),
                'milTotal' => array_sum($itemMilAry),
                'fsTotal' => $fsTotal,
                'workArea' => round($missionRet ['work_areas'], 2),
                'workTime' => round(($missionF200Ret ['work_times'] / 60) + $workTime, 2)
            )
        );
    }
    /**
     * 私有方法
     */


}